<template>
  <div id="depart">
    <div class="depart-top">
      部门编码名称：
      <el-input
        style="width: 240px; margin-right: 20px"
        placeholder="请输入部门编码，名称"
        v-model="relationName"
        clearable
      >
      </el-input>
      状态：
      <el-select
        v-model="statu"
        placeholder="状态"
        style="width: 120px; margin-right: 20px"
      >
        <el-option label="全部" value=""></el-option>
        <el-option label="启用" value="1"></el-option>
        <el-option label="禁用" value="2"></el-option>
      </el-select>
      <el-button type="primary" @click="selectRe()">查询</el-button>
      <el-button type="primary" @click="dialogFormVisible = true"
        >新增</el-button
      >
      <el-button type="primary" @click="able(ids)">启用</el-button>
      <el-button type="warning" @click="disable(ids)">禁用</el-button>
    </div>
    <div class="depart-content">
      <el-table
        height="500px"
        :data="treeDate"
        border
        row-key="relationId"
        default-expand-all
        @selection-change="handleSelectionChange"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        style="width: 100%; font-size: 13px; margin-left: 20px"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="relationId" label="部门编号" width="200">
        </el-table-column>
        <el-table-column prop="relationName" label="部门名称" width="200">
        </el-table-column>
        <el-table-column label="是否启用" width="120">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.statu"
              active-color="#66b1ff"
              inactive-color="#c1c1c1"
              :active-value="1"
              :inactive-value="2"
              @change="handleStatusChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button @click="de(scope.row)" type="text" size="small"
              >删除</el-button
            >
            <el-button
              @click="up(scope.row.relationId)"
              type="text"
              size="small"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      width="600px"
      top="60px"
      :title="rid ? '修改部门' : '新增部门'"
      :visible.sync="dialogFormVisible"
    >
      <AddDepart ref="addDepart" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="qu()">取 消</el-button>
        <el-button type="primary" @click="sure()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import AddDepart from "./AddDepart.vue";

export default {
  name: "Area",
  components: {
    AddDepart,
  },
  data() {
    return {
      id: "",
      dialogFormVisible: false,
      cid: 1,
      relationName: "",
      statu: "",
      selection: [],
      departs: [],
      treeDate: [],
      ids: [],
      upStatus: "",
      rid: "",
    };
  },
  methods: {
    qu() {
      this.$refs.addDepart.letNull();
      this.rid = "";
      this.dialogFormVisible = false;
    },
    up(id) {
      this.dialogFormVisible = true;
      this.rid = id;
      this.$nextTick(() => {
        if (this.$refs.addDepart) {
          this.$refs.addDepart.selectById(id);
        }
      });
    },
    de(ralation) {
      this.$confirm("此操作将删除该部门, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.axios({
            url: "/info/relation/selectCount",
            params: {
              parentId: ralation.relationId,
            },
          }).then((rs) => {
            if (rs.data.count > 0) {
              this.$message({
                showClose: true,
                message: "该部门下有其它部门不可以删除",
                type: "error",
              });
              return;
            }

            this.axios({
              url: "/info/relation/updateStatus",
              params: {
                statu: 0,
                ids: ralation.relationId,
              },
            }).then((rs) => {
              if (rs.data.code === 200) {
                this.selectRe();
                this.$message({
                  showClose: true,
                  message: "删除成功",
                  type: "success",
                });
              } else {
                this.$message({
                  showClose: true,
                  message: "删除失败",
                  type: "error",
                });
              }
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    disable(ids) {
      if (ids.length <= 0) {
        this.$message({
          showClose: true,
          message: "请选择部门",
          type: "error",
        });
        return;
      }
      this.upsta(ids, 2);
    },
    able(ids) {
      if (ids.length <= 0) {
        this.$message({
          showClose: true,
          message: "请选择部门",
          type: "error",
        });
        return;
      }
      this.upsta(ids, 1);
    },
    handleStatusChange(depart) {
      let ids = [];
      ids.push(depart.relationId);
      const statu = depart.statu;
      this.upsta(ids, statu);
    },
    upsta(ids, statu) {
      this.axios({
        url: "/info/relation/updateStatus",
        params: {
          ids: ids.toString(),
          statu,
        },
      }).then((rs) => {
        if (rs.data.code === 200) {
          this.selectRe();
          this.$message({
            showClose: true,
            message: "设置成功",
            type: "success",
          });
        } else {
          this.$message({
            showClose: true,
            message: "设置失败",
            type: "error",
          });
        }
      });
    },
    handleSelectionChange(selection) {
      console.log(selection);
      this.ids = selection.map((item) => item.relationId);
      console.log("IDs:", this.ids);
      this.selection = selection;
    },
    selectRe() {
      this.axios({
        url: "/info/relation/selectRe",
        params: {
          relationName: this.relationName,
          statu: this.statu,
        },
      })
        .then((rs) => {
          console.log(rs);
          this.departs = rs.data.ralation;
          if (this.relationName === "") {
            this.treeDate = this.buildTree(this.departs);
          } else {
            this.treeDate = this.departs;
          }
          console.log(this.departs);
          console.log(this.treeDate);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    buildTree(data) {
      const tree = [];
      const map = {};
      let com = this.cid;

      // 将所有节点添加到map中，方便后续查找
      data.forEach((item) => {
        map[item.relationId] = { ...item, children: [] };
      });

      // 构建树形结构
      data.forEach((item) => {
        console.log("Before building tree:", item);
        if (item.parentId === com) {
          // 如果父ID匹配，直接添加到树数组中
          tree.push(map[item.relationId]);
        } else {
          // 否则，找到父节点并添加到父节点的子节点数组中
          if (map[item.parentId]) {
            map[item.parentId].children.push(map[item.relationId]);
          }
        }
        console.log("After building tree:", tree);
        console.log(tree[0].statu);
      });

      return tree;
    },

    async sure() {
      const flag = await this.$refs.addDepart.addAndUp();
      if (flag == true) {
        this.dialogFormVisible = false;
        this.rid = "";
        this.selectRe();
      }
    },
  },
  created() {
    this.selectRe();
  },
};
</script>

<style scoped>
#depart {
  width: 100%;
  height: 100%;
}

.depart-top {
  width: calc(100% -20px);
  height: 60px;
  /* background-color: pink; */
  line-height: 60px;
  padding-left: 20px;
  font-size: 13px;
}

.depart-content {
  width: 100%;
  height: calc(100% - 60px);
  /* background-color: skyblue; */
}

.el-input,
.el-button {
  font-size: 13px;
}
</style>